package com.party.util;

import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;

@Slf4j
public class XMLAppendExample {
    public static void addXml(String url,String date) {
        try {
            // 加载和解析XML文件
            File file = new File("/www/wwwroot/moji_next_test/mojichibi_fe/public/sitemap.xml");
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(file);

            // 获取根元素
            Element root = doc.getDocumentElement();

            Element rootElement1 = doc.createElement("url");
            root.appendChild(rootElement1);

            // 创建子元素
            Element child0 = doc.createElement("loc");
            child0.appendChild(doc.createTextNode(url));
            rootElement1.appendChild(child0);

            // 创建子元素
            Element child1 = doc.createElement("lastmod");
            child1.appendChild(doc.createTextNode(date));
            rootElement1.appendChild(child1);

            // 创建子元素
            Element child2 = doc.createElement("changefreg");
            child2.appendChild(doc.createTextNode("always"));
            rootElement1.appendChild(child2);

            // 创建子元素
            Element child3 = doc.createElement("priority");
            child3.appendChild(doc.createTextNode("1.0"));
            rootElement1.appendChild(child3);

            // 写入新的XML到文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(file);

            transformer.transform(source, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
